<template>
  <div class="club-member-form">
    <h2>{{ isEdit ? '编辑社团成员' : '申请加入社团' }}</h2>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >
      <el-form-item label="所属社团" prop="clubId">
        <el-select v-model="form.clubId" placeholder="请选择社团" filterable
                  :disabled="isEdit || (isClubLeader && !isAdmin)">
          <el-option
            v-for="club in clubOptions"
            :key="club.id"
            :label="club.name"
            :value="club.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="用户" prop="userId" v-if="!isEdit && (isAdmin || isClubLeader)">
        <el-select v-model="form.userId" placeholder="请选择用户" filterable>
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="`${user.realName || ''}(${user.username})`"
            :value="user.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="用户" v-else>
        <el-input 
          :value="isEdit ? memberUserName : (userInfo.realName || '') + '(' + userInfo.username + ')'"
          disabled
          placeholder="用户信息"
        ></el-input>
      </el-form-item>
      
      <!-- <el-form-item label="积分" prop="points" v-if="isAdmin || isClubLeader">
        <el-input-number v-model="form.points" :min="0" placeholder="请输入积分"></el-input-number>
      </el-form-item> -->
      
      <!-- <el-form-item label="积分" v-else>
        <el-input 
          value="0" 
          disabled
          placeholder="积分"
        ></el-input>
      </el-form-item> -->
      
      <el-form-item label="状态" prop="status" v-if="isAdmin || isClubLeader">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="待审核" value="pending"></el-option>
          <el-option label="已通过" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" v-else>
        <el-input 
          value="待审核" 
          disabled
          placeholder="状态"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">{{ isEdit ? '保存' : '申请加入' }}</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getClubList } from '@/api/club'
import { getUserList } from '@/api/user'
import { getClubMemberDetail, addClubMember, updateClubMember } from '@/api/clubMember'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const clubOptions = ref([])
const userOptions = ref([])
const memberUserInfo = ref(null)
const memberUserName = computed(() => {
  if (memberUserInfo.value) {
    return `${memberUserInfo.value.realName || ''}(${memberUserInfo.value.username})`
  }
  return ''
})

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')
const isStudent = computed(() => userInfo.value.role === 'student')

// 是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive({
  clubId: null,
  userId: null,
  points: 0,
  status: isAdmin.value || isClubLeader.value ? 'approved' : 'pending'
})

// 表单校验规则
const rules = reactive({
  clubId: [
    { required: true, message: '请选择社团', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  points: [
    { required: true, message: '请输入积分', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 加载社团列表
const loadClubs = async () => {
  try {
    let params = { pageSize: 1000 }
    
    // 如果是社团负责人且不是管理员，只能看到自己管理的社团
    if (isClubLeader.value && !isAdmin.value) {
      params.leaderId = userInfo.value.id
    }
    
    const res = await getClubList(params)
    if (res.data && res.code === 200) {
      clubOptions.value = res.data.list
      
      // 如果是社团负责人且不是管理员，默认选择第一个社团
      if (isClubLeader.value && !isAdmin.value && clubOptions.value.length > 0) {
        form.clubId = clubOptions.value[0].id
      }
    } else {
      ElMessage.error(res.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const res = await getUserList({ pageSize: 1000 })
    if (res.data && res.code === 200) {
      userOptions.value = res.data.list
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取社团成员详情
const getMemberInfo = async (id) => {
  try {
    const res = await getClubMemberDetail(id)
    if (res.code === 200 && res.data) {
      // 填充表单数据
      form.clubId = res.data.clubId
      form.userId = res.data.userId
      form.points = res.data.points
      form.status = res.data.status
      
      // 记录用户信息用于显示
      memberUserInfo.value = res.data.user
    } else {
      ElMessage.error(res.message || '获取社团成员信息失败')
    }
  } catch (error) {
    console.error('获取社团成员详情出错:', error)
    ElMessage.error('获取社团成员信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 编辑社团成员
      const id = route.params.id
      const res = await updateClubMember(id, {
        points: 0,
        status: form.status
      })
      if (res.code === 200) {
        ElMessage.success('更新成功')
        goBack()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加社团成员（如果是学生申请，设置默认值）
      const submitData = {...form}
      
      // 如果是学生角色，设置默认值
      if (isStudent.value) {
        submitData.userId = userInfo.value.id
        submitData.points = 0
        submitData.status = 'pending'
      }
      
      const res = await addClubMember(submitData)
      if (res.code === 200) {
        ElMessage.success(isStudent.value ? '申请已提交，等待审核' : '添加成功')
        goBack()
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    // ElMessage.error(error)
  }
}

// 返回上一页
const goBack = () => {
  router.push('/club-members')
}

// 初始化
onMounted(() => {
  loadClubs()
  
  if (isEdit.value && route.params.id) {
    getMemberInfo(route.params.id)
  } else {
    // 如果是新增模式且是学生角色，默认使用当前用户ID
    if (isStudent.value) {
      form.userId = userInfo.value.id
    } else {
      loadUsers()  // 管理员和社团负责人才需要加载用户列表
    }
  }
})
</script>

<style scoped>
.club-member-form {
  padding: 20px;
}

.form-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 